package com.ckm.config.xss;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.text.StringEscapeUtils;

import java.io.IOException;
import java.util.Objects;

/**
 * 处理后端返回前端的json数据，进行数据转义
 */
public class XSSJsonStringSerializer extends JsonSerializer<String> {

    @Override
    public Class<String> handledType() {
        return String.class;
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (Objects.nonNull(s)){
            String string = StringEscapeUtils.escapeHtml4(s);
            jsonGenerator.writeString(string);
        }
    }
}
